﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Collections.Generic;

namespace RStein.PosterousReader.Common.UIHelpers
{
  public class UIHelper
  {
    public static string STATE_KEY_SEPARATOR = "_";
    public static string VIEW_SUFFIX = "View";
    public static string GetTransientStateKey(ElementIndexPair pair, FrameworkElement root)
    {
      if (pair.Element == null)
      {
        throw new ArgumentNullException("element");
      }

      if (root == null)
      {
        throw new ArgumentNullException("root");
      }

      if (pair.Element.Parent == null || pair.Element == root)
      {
        return pair.Element.GetType().FullName + pair.Index;
      }

      ElementIndexPair iterElement = pair;
      StringBuilder builder = new StringBuilder();


      while (iterElement != null)
      {        
        builder.Append(iterElement.Element.GetType().Name);
        builder.Append(iterElement.Index);        
        builder.Append(STATE_KEY_SEPARATOR);        
        iterElement = iterElement.Parent;        
      }

      return builder.ToString();
    }


    public static IEnumerable<ElementIndexPair> GetChildren(FrameworkElement element)
    {

      if (element == null)
      {
        throw new ArgumentNullException("element");
      }

      return getchildrenInner(element);
    }

    private static IEnumerable<ElementIndexPair> getchildrenInner(FrameworkElement element)
    {
      int childrenCount = VisualTreeHelper.GetChildrenCount(element);
      int sibblingIndex = 0;
      for (int currentIndex = sibblingIndex; currentIndex < childrenCount; currentIndex++)
      {
        var child = VisualTreeHelper.GetChild(element, currentIndex) as FrameworkElement;
        if (child == null)
        {
          continue;
        }


        yield return new ElementIndexPair
                          {
                            Index = sibblingIndex,
                            Element = child
                          };
        sibblingIndex++;


      }


    }
  }
}
